<template>
  <div class="book-detail">
    <el-card class="detail-card">
      <!-- 标签页切换 -->
      <el-tabs v-model="activeTab">
        <!-- 书籍详情标签页 -->
        <el-tab-pane label="书籍详情" name="detail">
          <loading-wrapper :loading="detailLoading">
            <!-- 原有的书籍详情内容 -->
            <div class="header-section">
              <div class="title-row">
                <div class="left-section">
                  <div class="title-wrapper">
                    <h2>{{ bookInfo.title }}</h2>
                    <el-button 
                      v-if="bookInfo.reading_url" 
                      type="primary"
                      link
                      class="reading-button"
                      @click="handleReadingLink(bookInfo.reading_url)"
                    >
                      <el-icon><Link /></el-icon>
                      在线阅读
                    </el-button>
                  </div>
                </div>
                <div class="right-section">
                  <!-- 评分区域 -->
                  <div class="rating-section">
                    <div class="current-rating">
                      <span class="rating-label">综合评分:</span>
                      <span class="rating-value">{{ Math.round(bookInfo.rating) }}分</span>
                      <span class="rating-text">{{ getRatingLevelText(Math.round(bookInfo.rating)) }}</span>
                      <span class="rating-count">({{ bookInfo.ratingCount }}人评分)</span>
                    </div>
                    <el-divider direction="vertical" />
                    <el-button 
                      type="primary" 
                      link 
                      @click="showRatingDialog"
                    >
                      <el-icon><Star /></el-icon>
                      {{ bookInfo.userRating ? '修改评分' : '评分' }}
                    </el-button>
                  </div>

                  <!-- 操作按钮区域 -->
                  <div class="action-buttons">
                    <el-divider direction="vertical" />
                    <el-button 
                      class="like-button"
                      :class="{ 'liked': bookInfo.isLiked }"
                      @click="handleLike"
                      link
                    >
                      <heart-outline-icon 
                        :size="20" 
                        :color="bookInfo.isLiked ? '#ff4757' : '#909399'"
                        :filled="bookInfo.isLiked"
                      />
                      <span class="like-count">{{ bookInfo.likeCount }}</span>
                    </el-button>
                    <el-divider direction="vertical" />
                    <el-button 
                      type="danger" 
                      link 
                      @click="handleReport"
                      class="report-button"
                    >
                      <el-icon><Warning /></el-icon>
                      举报
                    </el-button>
                  </div>
                </div>
              </div>
              <div class="meta-info">
                <span>作者：{{ bookInfo.author }}</span>
                <span>分享者：{{ bookInfo.nickname || bookInfo.username }}</span>
                <span>分享时间：{{ bookInfo.created_at }}</span>
              </div>
              <div class="tags">
                <el-tag 
                  v-for="tag in bookInfo.tags" 
                  :key="tag"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>

            <div class="content-section">
              <div class="book-cover">
                <!-- 轮播图组件 -->
                <el-carousel 
                  :interval="4000" 
                  height="400px"
                  v-if="bookInfo.images && bookInfo.images.length > 0"
                  @change="handleSlideChange"
                  ref="carouselRef"
                  trigger="click"
                  :autoplay="false"
                  indicator-position="none"
                  arrow="hover"
                >
                  <el-carousel-item 
                    v-for="(image, index) in bookInfo.images" 
                    :key="index"
                  >
                    <el-image
                      :src="image"
                      fit="cover"
                      class="carousel-image"
                      :preview-src-list="bookInfo.images"
                      :initial-index="currentImageIndex"
                      :preview-teleported="true"
                      loading="lazy"
                      @click="handleImageClick(index)"
                    >
                      <template #placeholder>
                        <div class="image-placeholder">
                          <el-icon><Picture /></el-icon>
                          <span>加载中</span>
                        </div>
                      </template>
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                          <span>加载失败</span>
                        </div>
                      </template>
                    </el-image>
                  </el-carousel-item>
                </el-carousel>

                <!-- 无图片时显示提示 -->
                <div v-else class="no-image-container">
                  <el-empty description="暂无图片" />
                </div>
              </div>
              <div class="book-content">
                <div class="thoughts-section">
                  <h3>读后感</h3>
                  <div 
                    class="thoughts-content"
                    :class="{ 'collapsed': isThoughtsCollapsed }"
                  >
                    {{ bookInfo.thoughts }}
                  </div>
                  <div 
                    v-if="shouldShowExpandButton"
                    class="expand-button"
                    @click="isThoughtsCollapsed = !isThoughtsCollapsed"
                  >
                    {{ isThoughtsCollapsed ? '展开全文😎🫣' : '收起🥳😉' }}
                    <el-icon :class="{ 'is-reverse': !isThoughtsCollapsed }">
                      <arrow-down />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </loading-wrapper>
        </el-tab-pane>

        <!-- 评论标签页 -->
        <el-tab-pane 
          label="评论"
          name="comments"
          lazy
        >
          <div class="comments-section">
            <div class="comments-header">
              <div class="comments-header-left">
                <h3>评论</h3>
                <el-select
                  v-model="sortBy"
                  placeholder="点赞排序"
                  class="sort-select"
                  :loading="commentsLoading"
                  @change="handleSortChange"
                >
                  <el-option label="最新评论" value="newest" />
                  <el-option label="点赞最多" value="mostLiked" />
                </el-select>
              </div>
              <el-button type="primary" @click="handleComment">评论</el-button>
            </div>
            
            <!-- 使用 LoadingWrapper 组件替换原有的加载状态处理 -->
            <loading-wrapper :loading="commentsLoading">
              <div class="comments-list">
                <el-empty 
                  v-if="!commentsLoading && comments.length === 0" 
                  description="暂无评论" 
                />
                <div 
                  v-else
                  v-for="comment in sortedComments" 
                  :key="comment.id" 
                  class="comment-item"
                >
                  <div class="comment-main">
                    <el-avatar 
                      :size="40" 
                      :src="comment.userAvatar"
                      @error="() => true"
                    >
                      {{ comment.nickname?.charAt(0) || comment.username?.charAt(0) }}
                    </el-avatar>
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="username">{{ comment.nickname || comment.username }}</span>
                        <span class="time">{{ comment.createTime }}</span>
                        <!-- 添加删除按钮 -->
                        <el-icon 
                          v-if="userStore.userInfo?.id === comment.user_id"
                          class="delete-icon"
                          @click="handleDeleteComment(comment.id)"
                        >
                          <Delete />
                        </el-icon>
                      </div>
                      <div class="comment-body">
                        <div class="comment-text">{{ comment.content }}</div>
                        <div class="comment-actions">
                          <div 
                            class="comment-like-button"
                            :class="{ 'liked': comment.isLiked }"
                            @click="handleCommentLike(comment)"
                          >
                            <heart-outline-icon 
                              :size="16" 
                              :color="comment.isLiked ? '#ff4757' : '#909399'"
                              :filled="comment.isLiked"
                            />
                            <span class="like-count">{{ comment.likeCount }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </loading-wrapper>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 评论对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="评论"
      width="500px"
      :before-close="handleClose"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form :model="commentForm" ref="commentFormRef" :rules="commentRules">
        <el-form-item label="评论内容" prop="content" required>
          <el-input
            v-model="commentForm.content"
            type="textarea"
            :rows="4"
            :maxlength="1000"
            placeholder="请输入您的评论..."
            resize="none"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitComment">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 举报对话框 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="举报内容"
      width="500px"
      class="report-dialog"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form 
        ref="reportFormRef"
        :model="reportForm"
        :rules="reportRules"
        label-width="100px"
      >
        <el-form-item label="举报类型" prop="reportType">
          <el-radio-group v-model="reportForm.reportType">
            <el-radio 
              v-for="option in reportTypeOptions"
              :key="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="举报原因" prop="reportReason">
          <el-input
            v-model="reportForm.reportReason"
            type="textarea"
            :rows="4"
            :maxlength="500"
            placeholder="请详细描述举报原因..."
            show-word-limit
            resize="none"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitReport">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 评分对话框 -->
    <el-dialog
      v-model="ratingDialogVisible"
      :title="bookInfo.userRating ? '修改评分' : '为这本书评分'"
      width="400px"
      align-center
    >
      <div class="rating-dialog-content">
        <div class="rating-options">
          <div 
            v-for="score in [1, 2, 3, 4, 5]" 
            :key="score"
            class="rating-option"
            :class="{ 'selected': userRating === score }"
            @click="userRating = score"
          >
            <span class="score">{{ score }}分</span>
            <span class="description">{{ getRatingDescription(score) }}</span>
            <el-rate
              :model-value="score"
              disabled
              :allow-half="false"
              :show-score="false"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ratingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRating" :disabled="!userRating">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star, Picture, Warning, Link, ArrowDown, Delete } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import HeartOutlineIcon from '@/components/icons/HeartOutlineIcon.vue'
import { getBookById, likeBook, unlikeBook, rateBook, getComments, addComment, likeComment, unlikeComment, deleteComment } from '@/api/book'
import { submitReport } from '@/api/report'
import { formatDateTime } from '@/utils/format'
import { wsClient } from '@/utils/websocket'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 修改登录状态的计算属性
const isLoggedIn = computed(() => userStore.isLoggedIn)

const commentsLoading = ref(false)  // 评论的加载状态

const bookInfo = ref({
  id: route.params.id,
  title: '',
  author: '',
  sharedBy: '',
  createTime: '',
  likeCount: 0,
  isLiked: false,
  tags: [],
  images: [],
  thoughts: '',
  rating: 0,
  ratingCount: 0,
  userRating: 0,
  reading_url: ''
})

// 标签页相关
const activeTab = ref('detail')

// 添加详情加载状态
const detailLoading = ref(false)

// 修改 loadBookDetail 函数
const loadBookDetail = async () => {
  detailLoading.value = true
  try {
    const userId = userStore.isLoggedIn ? userStore.userInfo.id : null
    const response = await getBookById(route.params.id, userId)
    if (response.code === 200) {
      bookInfo.value = {
        ...response.data,
        created_at: formatDateTime(response.data.created_at),
        isLiked: response.data.is_liked,
        userRating: response.data.user_rating || 0,
        rating: parseFloat(response.data.rating) || 0,
        ratingCount: parseInt(response.data.rating_count) || 0,
        likeCount: parseInt(response.data.like_count) || 0,
        tags: response.data.tags ? response.data.tags.split(/\s+/).filter(tag => tag) : [],
        images: (() => {
          try {
            if (!response.data.images) return [];
            
            // 如果已经是数组，直接返回
            if (Array.isArray(response.data.images)) {
              return response.data.images;
            }
            
            // 如果是字符串，尝试解析
            if (typeof response.data.images === 'string') {
              if (response.data.images.startsWith('data:')) {
                return [response.data.images];
              }
              // 否则尝试解析 JSON
              return JSON.parse(response.data.images);
            }
            
            return [];
          } catch (e) {
            console.error('解析图片数据失败:', e);
            // 如果解析失败但是有数据，可能是单个图片
            return response.data.images ? [response.data.images] : [];
          }
        })()
      }
      document.title = `详情-${bookInfo.value.title}`
      // 如果书籍已下架，提示并跳转
      if (bookInfo.value.status === 0) {
        ElMessage.warning('该书籍已下架或删除')
        router.push('/user/home')
        return
      }
    } else {
      ElMessage.error(response.message || '获取书籍详情失败')
    }
  } catch (error) {
    console.error('加载书籍详情失败:', error)
    ElMessage.error('加载失败，请稍后重试')
  } finally {
    detailLoading.value = false
  }
}

// 然后再定义 watch
watch(() => route.params.id, () => {
  loadBookDetail()
}, { immediate: true })

// 修改标签页切换监听 - 只处理评论加载
watch(activeTab, async (newTab) => {
  if (newTab === 'comments' && comments.value.length === 0) {
    await loadComments()
  }
})

// 修改评论排序选项
const sortOptions = [
  { label: '最新', value: 'newest' },
  { label: '点赞最多', value: 'mostLiked' }
]

// 添加排序相关的响应式变量
const comments = ref([])
const sortBy = ref('newest')
const sortedComments = ref([])

// 排序处理函数
const handleSortChange = (value) => {
  sortBy.value = value
  let sorted = [...comments.value]
  
  if (value === 'newest') {
    sorted.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
  } else if (value === 'mostLiked') {
    sorted.sort((a, b) => b.likeCount - a.likeCount)
  }
  
  sortedComments.value = sorted
}

// 监听评论数据变化，自动应用排序
watch(comments, () => {
  handleSortChange(sortBy.value)
}, { immediate: true })

// 加载评论列表
const loadComments = async () => {
  try {
    commentsLoading.value = true
    const userId = userStore.isLoggedIn ? userStore.userInfo.id : null
    const response = await getComments(route.params.id, userId)
    if (response.code === 200) {
      comments.value = response.data.map(comment => {
        // 保留原始的 user_id
        return {
          id: comment.id,
          content: comment.content,
          username: comment.user_name,
          userAvatar: comment.avatar_data,
          createTime: formatDateTime(comment.created_at),
          isLiked: Boolean(comment.is_liked),
          likeCount: parseInt(comment.like_count || 0),
          user_id: comment.user_id  // 确保保留原始的 user_id
        }
      })
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
  } finally {
    commentsLoading.value = false
  }
}

// 评论相关
const dialogVisible = ref(false)
const commentForm = ref({
  content: ''
})

// 添加评论表单验证规则
const commentRules = {
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 1, message: '评论内容不能为空', trigger: 'blur' }
  ]
}

// 添加评论表单引用
const commentFormRef = ref(null)

// 修改提交评论函数
const submitComment = async () => {
  if (!commentFormRef.value) return
  
  const trimmedContent = commentForm.value.content.trim()
  if (!trimmedContent) {
    ElMessage.warning('评论内容不能为空')
    return
  }
  
  try {
    const response = await addComment(bookInfo.value.id, { content: trimmedContent })
    if (response.code === 200) {
      // 重新加载评论列表以获取最新评论
      loadComments()
      
      // 清空表单
      commentForm.value.content = ''
      dialogVisible.value = false
      ElMessage.success('评论成功')
    }
  } catch (error) {
    ElMessage.error('评论失败，请稍后重试')
  }
}

// 修改关闭处理函数
const handleClose = () => {
  if (commentForm.value.content.trim()) {
    ElMessageBox.confirm(
      '确认关闭？未保存的内容将会丢失',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        dialogVisible.value = false
        commentForm.value = { content: '' }  // 清空内容
        if (commentFormRef.value) {
          commentFormRef.value.resetFields()  // 重置表单
        }
      })
      .catch(() => {
        // 用户取消关闭
      })
  } else {
    dialogVisible.value = false
    commentForm.value = { content: '' }  // 清空内容
    if (commentFormRef.value) {
      commentFormRef.value.resetFields()  // 重置表单
    }
  }
}

// 添加图片相关的状态
const currentImageIndex = ref(0)
const carouselRef = ref(null)

// 处理轮播图切换
const handleSlideChange = (index) => {
  currentImageIndex.value = index
}

// 处理图片点击
const handleImageClick = (index) => {
  currentImageIndex.value = index
}

// 上一张图片
const prevImage = () => {
  if (!carouselRef.value) return
  carouselRef.value.prev()
}

// 下一张图片
const nextImage = () => {
  if (!carouselRef.value) return
  carouselRef.value.next()
}

// 举报相关
const reportDialogVisible = ref(false)
const reportFormRef = ref(null)
const reportForm = ref({
  reportType: '',
  reportReason: ''
})

const reportTypeOptions = [
  { label: '内容不当', value: 'inappropriate' },
  { label: '垃圾信息', value: 'spam' },
  { label: '违法信息', value: 'illegal' },
  { label: '其他', value: 'other' }
]

const reportRules = {
  reportType: [
    { required: true, message: '请选择举报类型', trigger: 'change' }
  ],
  reportReason: [
    { required: true, message: '请输入举报原因', trigger: 'blur' },
    { min: 1, max: 200, message: '举报原因需要1-200字', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value && value.trim().length < 1) {
          callback(new Error('举报原因不能少于1个字符'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理举报
const handleReport = () => {
  reportDialogVisible.value = true
  reportForm.value = {
    reportType: '',
    reportReason: ''
  }
}

// 提交举报
const handleSubmitReport = async () => {
  if (!reportFormRef.value) return
  
  try {
    // 验证表单
    await reportFormRef.value.validate()

    // 发送举报请求
    await submitReport({
      postId: bookInfo.value.id,
      reportedUserId: bookInfo.value.user_id,
      reportType: reportForm.value.reportType,
      reportReason: reportForm.value.reportReason
    })
    
    ElMessage.success('提交成功')
    reportDialogVisible.value = false
  } catch (error) {
    if (error.name === 'ValidationError') return
    ElMessage.error(error.message || '举报失败')
  }
}

// 评分相关
const ratingDialogVisible = ref(false)
const userRating = ref(0)

// 显示评分对话框
const showRatingDialog = () => {
  userRating.value = bookInfo.value.userRating || 0
  ratingDialogVisible.value = true
}

// 修改提交评分的函数
const submitRating = async () => {
  try {
    const response = await rateBook(bookInfo.value.id, { score: userRating.value })
    if (response.code === 200) {
      // 重新加载书籍信息以获取最新评分
      loadBookDetail()
      ratingDialogVisible.value = false
      ElMessage.success('评分成功')
    }
  } catch (error) {
    ElMessage.error('评分失败，请稍后重试')
  }
}

// 获取评分描述
const getRatingDescription = (score) => {
  switch (score) {
    case 1: return '很差'
    case 2: return '较差'
    case 3: return '一般'
    case 4: return '好'
    case 5: return '非常棒'
    default: return ''
  }
}

// 获取评分等级文字
const getRatingLevelText = (score) => {
  switch (Math.round(score)) {
    case 5: return '（非常棒）'
    case 4: return '（很好）'
    case 3: return '（一般）'
    case 2: return '（较差)'
    case 1: return '（很差）'
    default: return ''
  }
}

// 添加读后感展开/收起相关的响应式变量
const isThoughtsCollapsed = ref(true)

// 计算是否需要显示展开按钮
const shouldShowExpandButton = computed(() => {
  // 如果文内容超过10行就显示展开按钮
  return bookInfo.value.thoughts.split('\n').length > 10 || 
         bookInfo.value.thoughts.length > 500 // 或者超过500个字符
})

// 处理评论点赞
const handleCommentLike = async (comment) => {
  try {
    // 保存当前状态
    const currentIsLiked = comment.isLiked
    const currentLikeCount = comment.likeCount
    
    // 先更新UI状态
    comment.isLiked = !currentIsLiked
    comment.likeCount += !currentIsLiked ? 1 : -1

    // 发送请求到服务器
    const response = await (currentIsLiked ? 
      unlikeComment(bookInfo.value.id, comment.id) : 
      likeComment(bookInfo.value.id, comment.id)
    )
    
    if (response.code !== 200) {
      // 如果请求失败，恢复原状态
      comment.isLiked = currentIsLiked
      comment.likeCount = currentLikeCount
      ElMessage.error('操作失败，请稍后重试')
    }
  } catch (error) {
    // 发生错误时恢复原状态
    comment.isLiked = currentIsLiked
    comment.likeCount = currentLikeCount
    console.error('评论点赞操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 修改书籍点赞的处理函数
const handleLike = async () => {
  try {
    if (bookInfo.value.isLiked) {
      await unlikeBook(bookInfo.value.id)
      bookInfo.value.isLiked = false
      bookInfo.value.likeCount--
    } else {
      await likeBook(bookInfo.value.id)
      bookInfo.value.isLiked = true
      bookInfo.value.likeCount++
    }
    console.log('点赞状态:', bookInfo.value.isLiked)
    console.log('点赞数:', bookInfo.value.likeCount)
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 修改评论处理函
const handleComment = () => {
  // 重置评论表单
  commentForm.value = { content: '' }
  if (commentFormRef.value) {
    commentFormRef.value.resetFields()
  }
  dialogVisible.value = true
}

// 修改处理阅读链接的方法
const handleReadingLink = async (url) => {
  if (!url) return
  
  try {
    await ElMessageBox.confirm(
      `您即将离开本站，去往第三方平台，请谨慎访问！`,
      '提示',
      {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 用户确认后，在新标签页中打开链接
    const finalUrl = url.startsWith('http') ? url : `https://${url}`
    window.open(finalUrl, '_blank')
  } catch (error) {
  }
}

// 修改图片预览相关代码
const handlePreview = (url) => {
  ElImageViewer.open([url])
}

// 处理书籍状态变化
const handleBookStatusChange = ({ bookId, status, isDelete }) => {
  if (parseInt(bookId) === parseInt(route.params.id) && status === 0) {
    ElMessage.warning('该书籍已下架或删除')
    router.push('/user/home')
  }
}

// 删除评论处理函数
const handleDeleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteComment(route.params.id, commentId)
    ElMessage.success('删除成功')
    // 重新获取评论列表
    await loadComments()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

onMounted(() => {
  loadBookDetail()
  // 连接 WebSocket
  wsClient.connect()
  // 监听书籍状态变化
  wsClient.on('book_status_change', handleBookStatusChange)
})

onUnmounted(() => {
  // 移除监听器
  wsClient.off('book_status_change', handleBookStatusChange)
})
</script>
<style scoped>
.book-detail {
  padding: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.header-section {
  margin-bottom: 30px;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.meta-info {
  color: #666;
  font-size: 14px;
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.tags {
  display: flex;
  gap: 10px;
}

.content-section {
  display: flex;
  gap: 30px;
  margin: 30px 0;
}

.book-cover {
  width: 400px;
  flex-shrink: 0; /* 防止图片区域被挤 */
}

.book-content {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
}

.thoughts-section {
  position: relative;
}

.thoughts-section h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #333;
}

.thoughts-content {
  font-size: 15px;
  line-height: 1.8;
  color: #1a1a1a;
  text-align: justify;
  letter-spacing: 0.3px;
  transition: max-height 0.3s ease;
}

/* 读后感展开/收起  判定高度*/
.thoughts-content.collapsed {
  max-height: 300px; 
  overflow: hidden;
}

.expand-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  margin-top: 12px;
  color: #409EFF;
  cursor: pointer;
  font-size: 14px;
  transition: opacity 0.3s;
}

.expand-button:hover {
  opacity: 0.8;
}

.expand-button .el-icon {
  transition: transform 0.3s;
}

.expand-button .el-icon.is-reverse {
  transform: rotate(180deg);
}

/* 响应式布局调整 */
@media screen and (max-width: 1200px) {
  .content-section {
    gap: 20px;
  }

  .book-cover {
    width: 350px;
  }
}

@media screen and (max-width: 992px) {
  .content-section {
    gap: 16px;
  }

  .book-cover {
    width: 300px;
  }
}

@media screen and (max-width: 768px) {
  .content-section {
    flex-direction: column;
  }

  .book-cover {
    width: 100%;
    max-width: 400px;
    margin: 0 auto;
  }

  .thoughts-content.collapsed {
    max-height: 250px; /* 在移动端显示更少的行数 */
  }
}

.carousel-image {
  width: 100%;
  height: 400px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s;
  background-color: #f8f9fa;
}

.carousel-image:hover {
  transform: scale(1.02);
}

.thumbnail-nav {
  display: flex;
  gap: 8px;
  overflow-x: auto;
  padding: 10px 0;
}

.thumbnail-item {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  opacity: 0.7;
  transition: all 0.3s;
}

.thumbnail-item:hover {
  opacity: 0.9;
}

.thumbnail-item.active {
  opacity: 1;
  border: 2px solid var(--el-color-primary);
}

.thumbnail-item .el-image {
  width: 100%;
  height: 100%;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.default-image-container {
  width: 100%;
  height: 400px;
  border-radius: 8px;
  overflow: hidden;
}

.default-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.el-carousel__item) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-carousel__item--card) {
  width: 400px;
}

:deep(.el-carousel__item--card.is-active) {
  transform: translateX(0) scale(1.05);
  z-index: 2;
}

.book-content {
  flex: 1;
}

.thoughts-content {
  line-height: 1.8;
  color: #333;
}

.comments-section {
  margin-top: 30px;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.comments-header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.comments-header-left h3 {
  margin: 0;
}

.sort-select {
  width: 120px;
}

.comment-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.comment-main {
  display: flex;
  gap: 15px;
  flex: 1;
  min-width: 0;
}

.comment-content {
  flex: 1;
  min-width: 0;
}

.comment-header {
  position: relative;
  display: flex;
  align-items: center;
  gap: 12px;
}

.comment-body {
  position: relative;
  padding-bottom: 24px; /* 为点赞按钮预留空间 */
}

.comment-text {
  color: #1a1a1a;
  font-size: 15px;
  line-height: 1.6;
  word-wrap: break-word;
  white-space: pre-wrap;
  max-width: 550px;
  font-weight: 400;
  letter-spacing: 0.3px;
  word-break: break-all;
}

.comment-actions {
  position: absolute;
  right: 0;
  bottom: 0;
  margin-top: 8px;
}

.comment-like-button {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
  color: #909399;
}

.comment-like-button:hover {
  background-color: rgba(144, 147, 153, 0.1);
}

.comment-like-button.liked {
  color: #ff4757;
}

.comment-like-button .like-count {
  font-size: 12px;
}

.delete-icon {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  cursor: pointer;
  font-size: 16px;
  
  &:hover {
    color: var(--el-color-danger);
  }
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #f8f9fa;
  padding: 8px 16px;
  border-radius: 8px;
}

.rating-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.current-rating {
  display: flex;
  align-items: center;
  gap: 4px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.like-button {
  display: flex !important;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.like-button:hover {
  background-color: rgba(144, 147, 153, 0.1);
}

.like-button.liked {
  color: #ff4757;
}

.like-button .like-count {
  font-size: 14px;
}

.report-button {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #f56c6c;
  padding: 4px 8px;
  z-index: 2;
  position: relative;
}

.report-button:hover {
  background-color: rgba(245, 108, 108, 0.1);
}

.rating-label {
  color: #666;
  font-size: 14px;
}

.rating-value {
  font-size: 16px;
  color: #ff9900;
  font-weight: bold;
}

.rating-text {
  color: #666;
  font-size: 14px;
}

.rating-count {
  color: #909399;
  font-size: 14px;
}

:deep(.el-divider--vertical) {
  height: 20px;
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.rating-dialog-content {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.rating-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.rating-option {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.rating-option:hover {
  background-color: #f5f7fa;
}

.rating-option.selected {
  background-color: #ecf5ff;
  color: var(--el-color-primary);
}

.rating-option .score {
  font-size: 16px;
  font-weight: bold;
  min-width: 40px;
}

.rating-option .description {
  color: #666;
}

.rating-option.selected .description {
  color: var(--el-color-primary);
}

.rating-text {
  color: #666;
  font-size: 14px;
  margin-right: 8px;
}

.rating-count {
  color: #909399;
  font-size: 14px;
  margin-left: 8px;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 8px;
}

.username {
  color: #909399;
  font-size: 14px;
}

.time {
  color: #909399;
  font-size: 14px;
  font-weight: normal;
}

/* 添加必填标记的样式 */
:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '*';
  color: var(--el-color-danger);
  margin-right: 4px;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 20px;
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
}

.create-time {
  color: #909399;
}

.report-dialog :deep(.el-form-item__label) {
  font-weight: bold;
}

.report-dialog :deep(.el-radio-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.reading-link {
  display: none;
}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title-wrapper h2 {
  margin: 0;
}

.reading-button {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  padding: 0;  /* 移除内边距 */
}

.reading-button .el-icon {
  font-size: 16px;
}

.comments-list {
  min-height: 200px;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  background-color: #f5f7fa;
}

.image-placeholder .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.report-dialog :deep(.el-form-item__label) {
  font-weight: bold;
}

.report-dialog :deep(.el-radio-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.delete-icon {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  cursor: pointer;
  font-size: 16px;
  
  &:hover {
    color: var(--el-color-danger);
  }
}
</style>
